import { message } from "antd";
import axios from "axios";

const apiConfig = {
    'development': {
        baseURL: "http://localhost:8081/api"
    },
    'production': {
        baseURL: "http://172.16.127.73:8848/api"
    }
}
console.log('process.env.NODE_ENV', process.env.NODE_ENV);
const baseURL = apiConfig[process.env.NODE_ENV || 'production'].baseURL;

class Http {
    constructor(baseURL) {
        this.setToken = this.setToken.bind(this)
        this.getToken = this.getToken.bind(this)
        this.http = axios.create({
            baseURL: baseURL,
            withCredentials: true,
            headers: {
                "Content-Type": "application/json",
                "Authorization": localStorage.getItem('token')
            },
        })
        this.http.interceptors.request.use((conig) => {
            const token = localStorage.getItem("token")
            if (token) {
                conig.headers.Authorization = `${token}`;
            }
            if (!token) {
                window.location.replace('/#/login');
            }
            return conig;
        })
        this.http.interceptors.response.use((response) => response, (error) => {
            try {
                console.log('error',error);
                if (error.response?.status === 401 && !error.config_retry) {
                    error.config_retry = true // 防止无限循环
                    const refreshToken = localStorage.getItem('refreshToken')
                    return axios.post(`${baseURL}/user/refresh-token?refreshToken=${refreshToken}`).then(async (newAuthToken) => {
                        const token = newAuthToken.data.data.token
                        this.http.defaults.headers.common.Authorization = `${token}`;
                        this.setToken(token)
                        return await this.http.request(error.config);
                    }).catch(err => {
                        const { response: { data = {} } = {} } = err
                        const {code:errorCode} = err 
                        const { code, msg } = data
                        console.log('errorCode',errorCode);
                        if ((code === 401 && msg === 'refreshToken无效') || errorCode === 'ERR_NETWORK') {
                            message.error("登录已过期，请重新登录！")
                            window.location.replace('/#/login');
                        }
                    });
                }
                if(error.response?.data?.status !== 200){
                    message.error('请求异常，请稍后重试！')
                    return Promise.reject(error);
                }
            } catch (error) {
                return Promise.reject(error);
            }
        })

    }

    getToken() {
        return localStorage.getItem("token")
    }

    setToken(token) {
        localStorage.setItem('token', token)
    }


    async get(endpoint, params) {
        try {
            const response = await this.http.get(endpoint, { params });
            return response.data;
        } catch (error) {
            console.error(error);
        }
    }

    async post(endpoint, data) {
        try {
            const response = await this.http.post(endpoint, data);
            return response.data;
        } catch (error) {
            console.error(error);
        }
    }

    async put(endpoint, data) {
        try {
            const response = await this.http.put(endpoint, data);
            return response.data;
        } catch (error) {
            console.error(error);
        }
    }

    async delete(endpoint) {
        try {
            const response = await this.http.delete(endpoint);
            return response.data;
        } catch (error) {
            console.error(error);
        }
    }
}

export default new Http(baseURL);
